<!-- 个人信息 -->
<template>
    <div>
        <div>
            <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                <a-form-item label="商户编号">
                    <div>{{merchantNo}}</div>
                </a-form-item>
                <a-form-item label="签名密钥">
                    <a-input v-model="signKey" :type="hasCode ? 'text' : 'password'" disabled placeholder="" >
                        <a-button type="primary" :disabled="smsSendBtn" slot="suffix" @click="getAuthCode(true)">重置密钥{{smsSendBtn ? `(${time})` : ''}}</a-button>
                    </a-input>
                </a-form-item>
                <a-form-item label="账户余额">
                    <div style="display: flex; align-items: center;">
                        <div style="display: flex; align-items: center; width: 200px">
                            <div style="margin-right: 50px">{{balance}}元</div>
                            <a-button type="primary" @click="transUserAccount()">充值</a-button>
                        </div>
                        <div style="display: flex; align-items: center">
                            <div class="setQuotaTitle" style="margin: 0 30px;">可用额度预警</div>
                            <a-switch style="margin: 0 30px;" disabled :checked="baAccount.status == '1' ? true : false" />
                            <div>(预警阈值：{{baAccount.warningThreshold}} <a href="javascript:void(0)" @click="setQuota(0)">修改</a>) </div>
                        </div>
                    </div>
                </a-form-item>
                <a-form-item label="账户授信额度" v-if="global.hasCreditcardAccount">
                    <div style="display: flex; align-items: center">
                        <div style="width: 200px">{{creditBalance}}元</div>
                        <div class="setQuotaTitle" style="margin: 0 30px;">可用额度预警</div>
                        <a-switch style="margin: 0 30px;" disabled :checked="creAccount.status == '1' ? true : false" />
                        <div>(预警阈值：{{creAccount.warningThreshold}} <a href="javascript:void(0)" @click="setQuota(7)">修改</a>) </div>
                    </div>
                </a-form-item>
                <a-form-item label="充值中金额">
                    <!-- <a-input v-model="freezeBalance" disabled placeholder="" ></a-input> -->
                    <div>{{freezeBalance}}元</div>
                </a-form-item>
                <a-form-item label="商户名称">
                    <!-- <a-input v-model="merchantName" disabled placeholder="" ></a-input> -->
                    <div>{{merchantName}}</div>
                </a-form-item>
                <a-form-item label="法人手机号">
                    <!-- <a-input v-model="legalPersonPhone" disabled placeholder="" ></a-input> -->
                    <div>{{legalPersonPhone}}</div>
                </a-form-item>
                <a-form-item label="法人姓名">
                    <!-- <a-input v-model="legalPersonName" disabled placeholder="" ></a-input> -->
                    <div>{{legalPersonPhone}}</div>
                </a-form-item>
                <a-form-item label="法人身份证号">
                    <!-- <a-input v-model="legalPersonIdCardNo" disabled placeholder="" ></a-input> -->
                    <div>{{legalPersonIdCardNo}}</div>
                </a-form-item>
                <a-form-item label="经营地址">
                    <!-- <a-input v-model="businessAddress" disabled placeholder="" ></a-input> -->
                    <div>{{businessAddress}}</div>
                </a-form-item>
                <a-form-item label="电子邮箱">
                    <!-- <a-input v-model="email" disabled placeholder="" ></a-input> -->
                    <div>{{email}}</div>
                </a-form-item>
                <a-form-item label="类型">
                    <a-radio-group v-model="type" >
                        <a-radio v-if="type == '2'" value="2">商户</a-radio>
                        <a-radio v-if="type == '1'" value="1">{{phone !=  '13602419403' ? '代理商' : '中控后台管理员'}}</a-radio>
                        <a-radio v-if="type == '0'" value="0">总平台</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item label="状态">
                    <a-radio-group v-model="status" >
                        <a-radio v-if="status == '1'" value="1">可用</a-radio>
                        <a-radio v-if="status == '0'" value="0">不可用</a-radio>
                    </a-radio-group>
                </a-form-item>
                <!-- <a-form-item  v-bind="formItemLayoutWithOutLabel">
                    <a-button type="primary" @click="register">立即注册</a-button>
                </a-form-item> -->
            </a-form>
        </div>

        <!-- 获取验证码 -->
        <a-modal
            :title="updateSignCode ? '修改签名密钥' : '查看密钥'"
            :visible="visible"
            width="80%"
            @ok="handOK"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="验证码">
                        <a-input v-model="authCode" placeholder="请输入验证码" allow-clear></a-input>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 余额互转 -->
        <a-modal
            :title="'余额充值'"
            :visible="visibleAccount"
            width="80%"
            @ok="handAccountOK"
            @cancel="visibleAccount = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="充值银行名称">
                        <a-input v-model="account.accountName" :disabled="true" placeholder="" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="充值银行账号">
                        <a-input v-model="account.account" :disabled="true" placeholder="" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="充值开户银行">
                        <a-input v-model="account.bankName" :disabled="true" placeholder="" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="充值金额">
                        <a-input v-model="amount" placeholder="请输入充值金额" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="公司名称">
                        <a-input v-model="transferAccount" placeholder="请输入公司名称" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="凭证上传">
                        <div class="clearfix">
                            <a-upload
                            list-type="picture-card"
                            :file-list="fileList"
                            @preview="handlePreview"
                            @change="handleChange"
                            >
                                <div v-if="fileList.length < 1">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">
                                        选择图片
                                    </div>
                                </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 额度阈值预警设置 -->
        <a-modal
            :title="accountType == 0 ? '余额阈值预警设置' : '授信额度阈值预警设置'"
            :visible="visibleQuota"
            width="80%"
            @ok="handQuotaOK"
            @cancel="visibleQuota = false"
            >
            <div>
                <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 17 }">
                    <a-form-item label="预警阈值">
                        <a-input v-model="warningThreshold" placeholder="请输入收款用户ID" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="预警号码">
                        <div class="flex" style="margin-bottom: 20px ">
                            <a-input v-model="mobile1" placeholder="请输入预警号码" allow-clear ></a-input>
                            <a-button v-if="phoneArr.length == 0" style="margin-left: 20px" type="" @click="addMobile()">+</a-button>
                        </div>
                        <div class="flex" style="margin-bottom: 20px " v-if="phoneArr.length > 0">
                            <a-input v-model="mobile2" placeholder="请输入预警号码" allow-clear ></a-input>
                            <a-button v-if="phoneArr.length == 1" style="margin-left: 20px" type="" @click="addMobile()">+</a-button>
                        </div>
                        <div class="flex" v-if="phoneArr.length == 2">
                            <a-input v-model="mobile3" placeholder="请输入预警号码" allow-clear ></a-input>
                        </div>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-radio-group v-model="quotaStatus" >
                            <a-radio value="0">关闭</a-radio>
                            <a-radio value="1">开启</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { resetExternalMerchantKey , queryExternalMerchantInfo , queryUserAccount , transferUserAccount , queryReleaseMerchantQuotaConfig , updateReleaseMerchantQuotaConfig , uploadTopUpEvidence } from '@/api/member';
import { isEmail } from '@/utils/util';
import { getSmsCaptcha , checkAuthCode } from '@/api/login';
import { queryBrandTopUpAccount } from '@/api/brand';
export default {
    data () {
        return {
            brandId: this.global.brandId,
            userId: sessionStorage.getItem('userId'),
            phone: '', // 注册手机号
            parentUserPhone: '', // 上级手机号
            formItemLayoutWithOutLabel: {
                wrapperCol: {
                    xs: { span: 24, offset: 0 },
                    sm: { span: 20, offset: 6 },
                },
            },
            merchantNo: '', // 商户号
            merchantName: '', // 商户名称
            legalPersonPhone: '', // 法人手机号
            legalPersonName: '', // 法人姓名
            legalPersonIdCardNo: '', // 法人身份证号码
            businessAddress: '', // 经营地址
            signKey: '', // 签名密钥
            email: '', // 电子邮箱
            type: '2', // 类型
            typeList: [
                { id: '0', name: '总平台' },
                { id: '1', name: '代理商' },
                { id: '2', name: '商户' },
            ],
            status: '1', // 状态 0：不可用，1：可用
            isShowParentPhone: false,
            smsSendBtn: false,
            time: 60,
            visible: false,
            authCode: '',
            id: '',
            balance: 0, // 账户余额
            freezeBalance: 0, // 冻结余额
            hasCode: true,
            updateSignCode: false,
            visibleAccount: false,
            receiveUserId: '', // 收款用户ID
            amount: '', // 转账金额
            payPassword: '', // 支付密码
            creditBalance: 0, // 授信额度
            baAccount: {
                status: '0',
                mobile: '',
                warningThreshold: 0,
            }, // 余额预警阈值信息
            creAccount: {
                status: '0',
                mobile: '',
                warningThreshold: 0,
            }, // 授信额度预警阈值信息
            accountType: 0,
            warningThreshold: 0,
            quotaStatus: '0',
            quotaMobile: [],
            visibleQuota: false,
            phoneArr: [],
            mobile1: '',
            mobile2: '',
            mobile3: '',
            fileList: [],
            transferAccount: '',
            account: {},
        };
    },
    beforeCreate() {
        this.form = this.$form.createForm(this, { name: 'dynamic_rule' });
    },
    created(){
        this.phone = sessionStorage.getItem('loginPhone')
        this.queryMerchant()
        this.getUserAccount()
        this.getUserAccount1()
        this.getAccount()
    },
    methods: {
        // 查询商户信息
        queryMerchant(){
            let _this = this;
            const params = {
                'userId': _this.userId,
                'brandId': _this.brandId,
                'page': 0,
                'size': 1,
            }
            queryExternalMerchantInfo(params)
            .then(res=>{
                if(res.success){
                    if(res.data.id){
                        var item = res.data
                        _this.merchantNo = item.merchantNo
                        _this.merchantName = item.merchantName
                        _this.signKey = item.signKey
                        _this.legalPersonPhone = item.legalPersonPhone
                        _this.legalPersonName = item.legalPersonName
                        _this.legalPersonIdCardNo = item.legalPersonIdCardNo
                        _this.businessAddress = item.businessAddress
                        _this.email = item.email
                        _this.type = item.type
                        _this.status = item.status
                        _this.signKey = item.signKey
                        _this.id = item.id
                        sessionStorage.setItem('userType',item.type)
                        sessionStorage.setItem('merchantNo',item.merchantNo)
                        _this.merchantNo = item.merchantNo
                        _this.getMerchantQuotaConfig(0)
                        _this.getMerchantQuotaConfig(7)
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 查询账户信息
        getUserAccount(){
            let _this = this
            const params = {
                'userId': _this.userId,
                'accountType': '0',
            }
            queryUserAccount(params)
            .then(res=>{
                if(res.success){
                    if(res.data.content.length > 0){
                        _this.balance = res.data.content[0].balance;
                        _this.freezeBalance = res.data.content[0].freezeBalance;
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        getUserAccount1(){
            let _this = this
            const params = {
                'userId': _this.userId,
                'accountType': '7',
            }
            queryUserAccount(params)
            .then(res=>{
                if(res.success){
                    if(res.data.content.length > 0){
                        _this.creditBalance = res.data.content[0].balance;
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 重置密钥
        getAuthCode(bool){
            console.log('获取验证码')
            let _this = this
            _this.smsSendBtn = true
            _this.visible = true
            _this.authCode = ''
            _this.updateSignCode = bool;
            const interval = window.setInterval(() => {
                if (_this.time-- <= 0) {
                    _this.time = 60
                    _this.smsSendBtn = false
                    window.clearInterval(interval)
                }
            }, 1000)
            const hide = this.$message.loading('验证码发送中..', 0)
            getSmsCaptcha({ receiveAccount: _this.phone }).then(res => {
                if(res.success){
                    setTimeout(hide, 500)
                    _this.$notification['success']({
                        message: '提示',
                        description: `验证码已发送至尾号${_this.phone.substring(_this.phone.length - 4)}的手机上，请注意查收。`,
                        duration: 8
                    })
                }else{
                    setTimeout(hide, 500)
                    _this.$notification['error']({
                    message: '提示',
                    description: res.errMessage,
                    duration: 8
                    })
                }
            })
        },
        // 确认修改签名密钥
        handOK(){
            let _this = this
            if(_this.authCode == ''){
                _this.$message.warning('请输入验证码');
                return;
            }
            if(_this.updateSignCode){
                _this.updateMerchantKey();
            }else{
                _this.lookMerhcantKey();
            }
        },
        // 重置密钥
        updateMerchantKey(){
            let _this = this
            const params = {
                'id': _this.id,
                'authCode': _this.authCode,
                'signKey': '29sdkj2'
            }
            resetExternalMerchantKey(params)
            .then(res=>{
                if(res.success){
                    _this.$notification['success']({
                        message: '提示',
                        description: '重置成功',
                        duration: 8
                    })
                    _this.queryMerchant()
                    _this.visible = false
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 查看密钥
        lookMerhcantKey(){
            let _this = this
            const params = {
                'authCode': _this.authCode,
            }
            checkAuthCode(params)
            .then(res=>{
                if(res.success){
                    _this.visible = false;
                    _this.hasCode = true;
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 余额互转
        transUserAccount(){
            this.receiveNo = '';
            this.amount = '';
            this.payPassword = '';
            this.visibleAccount = true;
        },
        // 通过商户编号查询商户信息
        queryMerchantByNo(){
            let _this = this
            return new Promise((resolve,reject) => {
                const params = {
                    'page': 0,
                    'size': 1,
                    'merchantNo': _this.receiveNo,
                    'brandId': _this.brandId,
                }
                queryExternalMerchantInfo(params)
                .then(res => {
                    if(res.success){
                        resolve(res.data.content);
                    }else{
                        resolve([])
                    }
                })
            })
        },
        // 确定转账
        async handAccountOK(){
            let _this = this
            if(_this.amount === ''){
                _this.$message.warning('请输入充值金额');
                return;
            }
            if(parseFloat(_this.amount) < 0 || isNaN(_this.amount)){
                _this.$message.warning('请输入正确的金额！')
                return;
            }
            if(_this.transferAccount === ''){
                _this.$message.warning('请输入公司名称');
                return;
            }
            if(_this.fileList.length == 0){
                _this.$message.warning('请上传充值凭证！')
                return;
            }
            const formData = new FormData();
            // const params = {
            //     'receiveUserId': _this.receiveUserId,
            //     'amount': _this.amount,
            //     'payPassword': _this.payPassword
            // }
            formData.append('tradeAmount',_this.amount);
            formData.append('userId',_this.userId);
            formData.append('transferAccount',_this.transferAccount)
            formData.append('evidenceType','1');
            // formData.append('img',_this.fileList[0])
            _this.fileList.forEach(item=>{
                formData.append('img',item.originFileObj)
            })
            uploadTopUpEvidence(formData)
            .then(res=>{
                if(res.success){
                    _this.visibleAccount = false;
                    _this.$notification['success']({
                        message: '提示',
                        description: '充值订单已提交，请等待审核！',
                        duration: 8
                    })
                    _this.getUserAccount()
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 获取商户额度配置
        getMerchantQuotaConfig(accountType){
            let _this = this
            const params = {
                'accountType': accountType,
                'brandId': _this.brandId,
                'merchantNo': _this.merchantNo,
                'userId': _this.userId,
            }
            queryReleaseMerchantQuotaConfig(params)
            .then(res=>{
                if(res.success){
                    if(res.data.content.length > 0){
                        if(accountType == 0){
                            _this.baAccount = JSON.parse(JSON.stringify(res.data.content[0]))
                        }else{
                            _this.creAccount = JSON.parse(JSON.stringify(res.data.content[0]))
                        }
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        setQuota(accountType){
            this.accountType = accountType;
            if(accountType == 0){
                this.quotaStatus = this.baAccount.status;
                this.quotaMobile = this.baAccount.mobile != '' && this.baAccount.mobile ? this.baAccount.mobile.split(',') : []
                this.warningThreshold = this.baAccount.warningThreshold;
            }else{
                this.quotaStatus = this.creAccount.status;
                this.quotaMobile = this.creAccount.mobile != '' && this.creAccount.mobile ? this.creAccount.mobile.split(',') : []
                this.warningThreshold = this.creAccount.warningThreshold;
            }
            console.log(this.quotaMobile,'this.quotaMobile')
            this.mobile1 = '';this.mobile2 = '';this.mobile3 = '';
            for(let i = 0; i < this.quotaMobile.length; i++){
                if(i == 0){
                    this.mobile1 = this.quotaMobile[i]
                }
                if(i == 1){
                    this.mobile2 = this.quotaMobile[i]
                }
                if(i == 2){
                    this.mobile3 = this.quotaMobile[i]
                }
            }
            this.phoneArr = this.quotaMobile
            this.visibleQuota = true;
        },
        // 设置额度阈值
        handQuotaOK(){
            let _this = this
            if(_this.warningThreshold == 0 || _this.warningThreshold < 0){
                _this.$message.warning('请输入正确的预警阈值！');
                return;
            }
            if(_this.mobile1 == '' && _this.mobile2 == '' && _this.mobile3 == ''){
                _this.$message.warning('请输入接受预警短信的手机号码！');
                return;
            }else{
                if(_this.mobile1 != '' && _this.mobile1.length != 11){
                    _this.$message.warning('请输入正确的接受预警短信的手机号码！');
                    return;
                }
                if(_this.mobile2 != '' && _this.mobile2.length != 11){
                    _this.$message.warning('请输入正确的接受预警短信的手机号码！');
                    return;
                }
                if(_this.mobile3 != '' && _this.mobile3.length != 11){
                    _this.$message.warning('请输入正确的接受预警短信的手机号码！');
                    return;
                }
            }
            var mobileList = [];
            if(_this.mobile1 != ''){
                mobileList.push(_this.mobile1)
            }
            if(_this.mobile2 != ''){
                mobileList.push(_this.mobile2)
            }
            if(_this.mobile3 != ''){
                mobileList.push(_this.mobile3)
            }
            const params = {
                'id': _this.accountType == 0 ? this.baAccount.id : this.creAccount.id,
                'brandId': _this.brandId,
                'userId': _this.userId,
                'accountType': _this.accountType,
                'warningThreshold': _this.warningThreshold,
                'mobile': mobileList.join(','),
                'status': _this.quotaStatus,
            }
            updateReleaseMerchantQuotaConfig(params)
            .then(res=>{
                if(res.success){
                    _this.visibleQuota = false;
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.accountType == 0 ? '余额阈值预警设置成功！' : '授信额度阈值预警设置成功！',
                        duration: 8
                    })
                    _this.getMerchantQuotaConfig(_this.accountType)
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        addMobile(){
            this.phoneArr.push(1);
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        handleChange({ fileList }) {
            this.fileList = fileList;
        },
        handleCancel() {
            this.previewVisible = false;
        },
        // 查询对公账户信息
        getAccount(){
            let _this = this
            // _this.account = JSON.parse(JSON.stringify(_this.accountInit))
            const params = {
                'brandId':_this.brandId,
                'evidenceType':'1'
            }
            queryBrandTopUpAccount(params)
            .then(res=>{
                if(res.success){
                    if(res.data.content.length > 0){
                        _this.account = res.data.content[0]
                    }
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
    }
}

</script>
<style scoped>
.setQuotaTitle{
    font-weight: 600;
    text-decoration:underline;
    color: #333;
}
</style>